package com.qf.commons.web.exception;

import com.qf.commons.core.exception.IExceptionListener;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/**
 * description: 业务接口的异常统一处理 - AOP
 * author: Ken
 * 公众号：Java架构栈
 */
@Aspect
@Slf4j
public class ControllerExceptionHandler {

    @Autowired(required = false)
    private List<IExceptionListener> exceptionListeners;

    @Around("@within(org.springframework.web.bind.annotation.RestController)")
    public Object exceptionHandler(ProceedingJoinPoint joinPoint) throws Throwable {

        Object result = null;
        //放行
        try {
            result = joinPoint.proceed();
        } catch (Throwable t) {
            
            //发现异常，调用监听器处理
            if(exceptionListeners != null) {
                log.debug("[Exception Listener] 异常监听器触发 - {}", exceptionListeners);
                for (IExceptionListener exceptionListener : exceptionListeners) {
                    exceptionListener.exceptionListener(t);
                }
            }
            //异常统一往外抛
            throw t;
        }
        return result;
    }
}
